import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hxdj/common/base_page/my_loading_page.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/components/underline_tab.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/home/select_service_time/select_service_time_viewmode.dart';
import 'package:provider/provider.dart';

class SelectServiceTimePage extends StatefulWidget {
  final Map<String, dynamic>? object;

  const SelectServiceTimePage({super.key, this.object});

  @override
  State<SelectServiceTimePage> createState() => _SelectServiceTimePageState();
}

class _SelectServiceTimePageState extends State<SelectServiceTimePage> with TickerProviderStateMixin {
  List<String> tabs = [];

  late TabController? _tabController;

  late SelectServiceTimeViewModel? viewModel;

  //选择的时间
  late String selectDayTime = "";
  @override
  void initState() {
    selectDayTime = widget.object?["serviceTime"];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BasePage<SelectServiceTimeViewModel>(
      onModelReady: (model) async {
        // 页面初始化完成后的回调
        viewModel = model;
        viewModel?.requestData(tId: widget.object?["tId"]);
      },
      viewModel: SelectServiceTimeViewModel(),
      builder: (BuildContext context, SelectServiceTimeViewModel model, Widget? child) {
        switch (model.state) {
          case ViewState.loading:
            final screenSize = MediaQuery.of(context).size;
            return Container(
                decoration: BoxDecoration(
                    color: MyColours.materialBg,
                    borderRadius: BorderRadius.only(topRight: Radius.circular(14.w), topLeft: Radius.circular(14.w))),
                width: screenSize.width,
                height: screenSize.height - kToolbarHeight - 34.h,
                child: const MyLoadingWidget());

          default:
            tabs.clear();
            for (ServiceTimeModel element in model.dataList) {
              tabs.add(element.dayTxt!);
            }
            _tabController = TabController(initialIndex: viewModel!.selectIndex, length: tabs.length, vsync: this);

            // _tabController!.removeListener(() {});

            // // 监听TabBarView的滚动事件
            // _tabController!.addListener(() {
            //   // 获取当前显示的TabBarView的索引
            //   int currentIndex = _tabController!.index;
            //   // 更新selectIndex的值
            //   viewModel!.selectIndexChange(currentIndex);
            // });
            return Consumer<SelectServiceTimeViewModel>(builder: (context, value, child) {
              return _buildListTab();
            });
        }
      },
    );
  }

  List<Widget> _buildTabWidget() {
    List<Widget> tabsWidget = [];

    tabsWidget = tabs.map((e) {
      int index = tabs.indexOf(e);
      ServiceTimeModel serviceTimeModel = viewModel!.dataList[index];
      return Column(
        children: [
          MyText(
            e,
            fontSize: 15.sp,
            color: viewModel!.selectIndex == index ? MyColours.appMain : MyColours.textBlack,
            fontWeight: FontWeight.w600,
          ),
          MyText(serviceTimeModel.week!,
              fontSize: 11.sp, color: viewModel!.selectIndex == index ? MyColours.appMain : MyColours.textBlack),
        ],
      );
    }).toList();

    return tabsWidget;
  }

  Widget _buildTabViewWidget(ServiceTimeModel serviceTimeModel) {
    return Container(
        padding: const EdgeInsets.all(10),
        child: GridView.builder(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 85.w, childAspectRatio: 85.w / 40.h, crossAxisSpacing: 6.w, mainAxisSpacing: 6.w),
            itemCount: serviceTimeModel.orderTime!.length,
            itemBuilder: (BuildContext ctx, index) {
              String orderTime = serviceTimeModel.orderTime![index];

              String currentDayTime = "${serviceTimeModel.days!} $orderTime";

              return MyTapWidget(
                onTap: () {
                  selectDayTime = "${serviceTimeModel.days!} $orderTime";
                  setState(() {});
                },
                child: MyBorder(
                    backgroundColor:
                        currentDayTime == selectDayTime ? MyColours.appMain.withOpacity(0.4) : MyColours.colorF6F6F6,
                    radius: 5.5.w,
                    child: Container(
                        alignment: Alignment.center,
                        child: MyText(serviceTimeModel.orderTime![index],
                            color: currentDayTime == selectDayTime ? MyColours.appMain : MyColours.textBlack,
                            fontSize: 13.sp))),
              );
            }));
  }

  Widget _buildListTab() {
    final screenSize = MediaQuery.of(context).size;

    return Container(
      decoration: BoxDecoration(
          color: MyColours.materialBg,
          borderRadius: BorderRadius.only(topRight: Radius.circular(14.w), topLeft: Radius.circular(14.w))),
      width: screenSize.width,
      height: screenSize.height - kToolbarHeight - 34.h,
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
            child: Container(
                alignment: Alignment.center,
                child: Text(
                  "请选择服务时间",
                  style: TextStyle(fontSize: 17.sp, fontWeight: FontWeight.w700),
                )),
          ),
          Container(
            color: Colors.white,
            child: TabBar(
              dividerColor: Colors.transparent,
              controller: _tabController,
              onTap: (value) {
                // 切换TabBarView时，更新selectIndex的值
                viewModel!.selectIndexChange(value);
              },
              indicator: const CAUnderlineTabIndicator(
                  indicatorBottom: 1,
                  indicatorWidth: 30,
                  isRound: true,
                  borderSide: BorderSide(
                    width: 3,
                    color: MyColours.appMain,
                  )),
              padding: EdgeInsets.only(bottom: 5.h),
              indicatorPadding: EdgeInsets.only(bottom: -5.h),
              tabs: _buildTabWidget(),
            ),
          ),
          MyGaps.line,
          Expanded(
              child: TabBarView(
            controller: _tabController,
            physics: const NeverScrollableScrollPhysics(),
            children: viewModel!.dataList.map((e) {
              return _buildTabViewWidget(e);
            }).toList(),
          )),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 15.w),
            margin: EdgeInsets.only(top: 15.h, bottom: 10.h),
            child: MyText(
              "因交通因素，实际到达可能会有30分钟浮动，请你知悉～",
              color: MyColours.textBlack,
              fontSize: 11.sp,
            ),
          ),
          GestureDetector(
            onTap: () async {
              dynamic selectCallback = widget.object!["onSelectCallback"];
              if (selectDayTime.isEmpty) {
                EasyLoading.showToast("请选择服务时间");
                return;
              }

              if (selectCallback != null) {
                selectCallback(selectDayTime);
              }
              // 关闭弹窗
              Navigator.of(context).pop();
            },
            child: SafeArea(
              child: Container(
                margin: EdgeInsets.only(top: 10.h, bottom: 15.h),
                padding: EdgeInsets.symmetric(horizontal: 15.w),
                child: Container(
                  padding: EdgeInsets.symmetric(vertical: 12.h),
                  decoration: BoxDecoration(
                    color: MyColours.appMain,
                    //设置四周圆角 角度
                    borderRadius: BorderRadius.circular(25.w),
                  ),
                  alignment: Alignment.center,
                  child: Text("确定预约此时间", style: MyTextStyles.textWhiteBold16),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
